package spring.cloud.tasks.executor.listener.task_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.node.TaskNodePaths;

@Slf4j
@Setter
@Getter
public final class ExecutorNode {

    /**
     * 执行服务器信息根节点.
     */
    public static final String ROOT = "executors";
    /**
     * 执行服务器对应的Executor运行节点
     */
    public static final String EXECUTOR = ROOT + "/%s";
    public static final String EXECUTOR_IP = ROOT + "/%s/ip";
    public static final String EXECUTOR_STATUS = ROOT + "/%s/status";
    public static final String EXECUTOR_PROCESS_SUCCESS_COUNT = ROOT + "/%s/processSuccessCount";
    public static final String EXECUTOR_PROCESS_FAILURE_COUNT = ROOT + "/%s/processFailureCount";
    public static final String EXECUTOR_RUN_ONE_TIME = ROOT + "/%s/runOneTime";
    public static final String EXECUTOR_STOP_ONE_TIME = ROOT + "/%s/stopOneTime";

    private ExecutorNode() {
    }

    /**
     * 对应的Executor运行节点
     */
    static String getExecutorNodePath(String executorId) {
        return String.format(EXECUTOR, executorId);
    }

    static String getIpNode(String executorId) {
        return String.format(EXECUTOR_IP, executorId);
    }

    static String getStatusNode(String executorId) {
        return String.format(EXECUTOR_STATUS, executorId);
    }

    static String getProcessSuccessCountNode(String executorId) {
        return String.format(EXECUTOR_PROCESS_SUCCESS_COUNT, executorId);
    }

    static String getProcessFailureCountNode(String executorId) {
        return String.format(EXECUTOR_PROCESS_FAILURE_COUNT, executorId);
    }

    static String getRunOneTimePath(String executorId) {
        return String.format(ExecutorNode.EXECUTOR_RUN_ONE_TIME, executorId);
    }

    static String getStopOneTimePath(String executorId) {
        return String.format(ExecutorNode.EXECUTOR_STOP_ONE_TIME, executorId);
    }


    /**
     * @return 运行态的server的ZK节点路径
     */
    public static String getExecutorNode(final String taskId, String executorId) {
        return TaskNodePaths.getTaskNodePath(taskId, getExecutorNodePath(executorId));
    }

    public static String getExecutorRoot(final String taskId) {
        return TaskNodePaths.getTaskNodePath(taskId, ROOT);
    }

    public static boolean isRunOneTimePath(final String taskId, String path, String executorId) {
        return path.startsWith(TaskNodePaths.getTaskNodePath(taskId, String.format(ExecutorNode.EXECUTOR_RUN_ONE_TIME, executorId)));
    }

    public static boolean isStopOneTimePath(final String taskId, String path, String executorId) {
        return path.startsWith(TaskNodePaths.getTaskNodePath(taskId, String.format(ExecutorNode.EXECUTOR_STOP_ONE_TIME, executorId)));
    }
}
